# 学生管理系统

# 菜单
import sys
import os

# 用列表存储这些学生对象
s_list = []
# 定义number记录列表下标
number = 0


def menu():
    print("------------------------------------------")
    print("           欢迎进入学生管理系统！！！           ")
    print("------------------------------------------")


# 进行操作选择：
def operate():
    print("------------------------------------------")
    print("     1. 新增学生信息       2. 显示学生信息      ")
    print("     3. 查找学生信息       4. 删除学生信息      ")
    print("                0. 退出程序                 ")
    print("------------------------------------------")
    count = input("请输入你选择的操作：")
    return count


def save():
    """
    存档函数
    """
    with open('D:/code/python/student_manage/record.txt', 'w', encoding='utf8') as f:
        for s in s_list:
            f.write(f"{s['studentId']}\t{s['name']}\t{s['gender']}\t{s['score']}\n")
        print(f"[存档成功] 共存储了 {len(s_list)} 条记录!")


def load():
    """
    读档函数
    """
    # 如果存档文件不存在, 则跳过读档环节
    if not os.path.exists('D:/code/python/student_manage/record.txt'):
        return
    # 先清空全局变量里的数据
    global s_list
    s_list = []
    with open('D:/code/python/student_manage/record.txt', 'r', encoding='utf8') as f:
        for line in f:
            # 针对这一行数据, 按照 \t 进行切分操作!
            # 去除末尾的换行符
            line = line.strip()
            tokens = line.split('\t')
            if len(tokens) < 4:
                print(f"文件格式有误! line={line}")
                continue
            student = {
                'studentId': tokens[0],
                'name': tokens[1],
                'gender': tokens[2],
                'className': tokens[3]
            }
            s_list.append(student)
        print(f"[读档成功] 共读取了 {len(s_list)} 条记录!")


def insert():
    global number
    print("新增学生开始")
    # 用字典来存储学生信息
    studentId = input("请输入学生编号：")
    name = input("请输入学生姓名：")
    gender = input("请输入学生性别：")
    if gender not in ["男", "女"]:
        print("您输入的性别有误，新增学生失败")
        return
    score = int(input("请输入学生成绩："))
    if score not in range(0, 101):
        print("您输入的成绩不在范围内(0,100)，新增学生失败")
        return
    student = {"studentId": studentId, "name": name, "gender": gender, "score": score}

    # 插入
    global s_list
    s_list.append(student)
    number += 1
    # 增加保存操作
    save()
    print("新增学生完毕！")


def show():
    print("显示学生信息开始")
    print(f"studentId\tname\tgender\tscore")
    for s in s_list:
        print(f"{s['studentId']}\t{s['name']}\t{s['gender']}\t{s['score']}")
    print(f"显示学生信息完毕！总共显示{number}名学生")


def find():
    print("根据学生姓名查找学生信息")
    elem = input("请输入想要查找的学生姓名：")
    total = 0
    for s in s_list:
        if s['name'] == elem:
            print(f"{s['studentId']}\t{s['name']}\t{s['gender']}\t{s['score']}")
            total += 1
    if total == 0:
        print(f"未找到姓名为:{elem}的学生")
    else:
        print(f"找到姓名为:{elem}的学生共{total}名！")


def delete():
    elem = input("请输入你所要删除学生的姓名：")
    line = 0
    flag = 0
    for s in s_list:
        if s['name'] == elem:
            s_list.pop(line)
            flag += 1
            global number
            number -= 1
        line += 1
    save()
    if flag:
        print("删除学生完毕！！！")
    else:
        print(f"未查找到姓名为:{elem}的学生，删除失败！")


# 入口函数
def main():
    load()
    # 菜单
    menu()
    while True:
        count = operate()
        if count == '1':
            insert()
        elif count == '2':
            show()
        elif count == '3':
            find()
        elif count == '4':
            delete()
        elif count == '0':
            # 退出 终止程序
            sys.exit(0)
        else:
            print("您的输入有误，请重新输入")
            continue
    return 0


main()
